﻿using UnityEngine;
using System.Collections;

public class Marble : Actors 
{
	// Use this for initialization
	
	public Texture[] m_Textures;
	public float m_Friction;
	public float m_Bounciness;
	public float m_MinVelocityX;
	public float m_MaxVelocityX;
	public float m_JumpForce;
	
	private bool m_IsTouchingGround = false;
	private int m_CollisionCount = 0;
	
	private void Start () 
	{
		int randomTexture = (int)Mathf.Floor(Random.Range(0, m_Textures.Length));
		
		aRenderer.material.mainTexture = m_Textures[randomTexture];
		aCollider.material.dynamicFriction = m_Friction;
		aCollider.material.staticFriction = m_Friction;
		aCollider.material.bounciness = m_Bounciness;
		
	}
	
	// Update is called once per frame
	private void Update () 
	{		
		CheckOnGround();
		VelocityLimit();
		
		if(Input.GetMouseButtonDown(0) && m_IsTouchingGround)
		{
			Debug.Log("MOUSE PRESSED");	
			//aGameObject.rigidbody.AddForce(0, 500, 0);
			//aRigidbody.AddForce(0, m_JumpForce, 0);
			//aRigidbody.velocity = new Vector3(aRigidbody.velocity.x, m_JumpForce, 0);
			aRigidbody.velocity += new Vector3(0, m_JumpForce, 0);
		}
		//Debug.Log(aRigidbody.velocity);
		Debug.Log(m_IsTouchingGround);
	}
	
	private void OnCollisionEnter(Collision other)
	{
		if(other.transform.tag == "Platform")
		{
			m_CollisionCount++;
			//m_IsTouchingGround = true;
		}
	}
	
	private void OnCollisionExit(Collision other)
	{
		if(other.transform.tag == "Platform" && m_IsTouchingGround)
		{
			m_CollisionCount--;
			//m_IsTouchingGround = false;
		}			
	}
	
	private void CheckOnGround()
	{
		if(m_CollisionCount > 0)
		{
			m_IsTouchingGround = true;			
		}
		else
		{
			m_IsTouchingGround = false;	
			
		}
	}
	
	private void VelocityLimit()
	{
		if(aRigidbody.velocity.x < m_MinVelocityX)
		{
			Vector3 minVel = aRigidbody.velocity;
			minVel.x = m_MinVelocityX;
			aRigidbody.velocity = minVel;	
		}
		else if(aRigidbody.velocity.x > m_MaxVelocityX)
		{
			Vector3 maxVel = aRigidbody.velocity;
			maxVel.x = m_MaxVelocityX;
			aRigidbody.velocity = maxVel;	
		}
	}
			
	//private void FixedUpdate()
	//{
    //    Quaternion deltaRotation = Quaternion.Euler(aRigidbody.angularVelocity * aRigidbody.velocity.x);
	//	aRigidbody.MoveRotation(deltaRotation);		
	//}
}
